<template>
  <div class="wrap webchat-summary">
    <el-aside class="card" style="width:160px">
      <el-card :body-style="{padding: '0 10px'}">
        <div class="card-item">
          <p class="num">{{summary.allSession || 0}}</p>
          <p class="num-word">{{$t('monitor.sessionNumToday')}}</p>
        </div>
        <div class="card-item">
          <p class="num">{{summary.dealingSession || 0}}</p>
          <p class="num-word">{{$t('monitor.dealingSession')}}</p>
        </div>
        <div class="card-item">
          <p class="num">{{summary.closeSession || 0}}</p>
          <p class="num-word">{{$t('monitor.sessionNumTodayAnswer')}}</p>
        </div>
        <div class="card-item">
          <!--Todo-->
          <p class="num">{{summary.closeSession | rate(summary.allSession)}}</p>
          <p class="num-word">{{$t('monitor.completeRate')}}</p>
        </div>
        <div class="card-item">
          <p class="num">{{summary.accessSession}}</p>
          <p class="num-word">{{$t('monitor.agentManual')}}</p>
        </div>
        <div class="card-item">
          <p class="num">{{summary.waitClaim || 0}}</p>
          <p class="num-word">{{$t('monitor.waitingSessionNum')}}</p>
        </div>
      </el-card>
    </el-aside>
    <div class="main1">
      <!--<div class="agent" style="margin-bottom: 25px">-->
        <!--<div v-for="item in licenceType" :key="item._id" class="agent-cont">-->
          <!--<span class="agent-title">{{item.label}}</span><span class="padding-r">已登录座席：{{item.online}}</span><span>开通座席：{{item.value1}}</span>-->
        <!--</div>-->
        <!--<div style="clear: both"></div>-->
      <!--</div>-->
      <div class="tips" v-if="$store.state.session.user.type === 'agent'">{{$t('monitor.tips2')}}</div>
      <affix :label="$t('monitor.webchatMonitor')" :bodyStyle="{paddingTop:'6px'}" v-once></affix>
      <el-container >
        <el-main class="main">
          <div class="header clearBoth">
            <time class="header-time">{{$t('monitor.currTime')}}：{{commonData.time}}</time>
            <div class="fr">
              <span>{{$t('monitor.showTable')}}</span>
              <el-select v-model="showTable" multiple collapse-tags :placeholder="$t('public.all')" size="mini" class="mulit-select">
              <el-option
                v-for="(item, index) in showOptions"
                :key="index"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
            </div>
          </div>
          <el-row :gutter="60">
            <el-col :span="12" class="border-line" v-if="!showTable.length || showTable.indexOf('1')!== -1">
              <div class="title">{{$t('monitor.webchatAgentMonitor')}}
                <el-popover
                  placement="bottom"
                  width="400"
                  trigger="hover"
                  popper-class="common-tootip"
                >
                  <div v-html="$t('monitor.tooltipWebchatAgent')"></div>
                  <span slot="reference" class="tooltip"><i class="iconfont icon-wenzishuoming"></i></span>
                </el-popover>
                <i class="iconfont icon-peizhi" @click="monitorWarn('agents')"></i>
              </div>
              <el-row :gutter="10">
                <div class="pie"><span class="pie-out">{{$t('monitor.logout2')}}{{pieData.out}}</span><span>{{$t('monitor.login2')}}{{pieData.on}}</span></div>
                <monitor-pie :data="pieData.pie" style="height: 260px;"></monitor-pie>
              </el-row>
            </el-col>
            <el-col :span="12" class="monitor-table" v-if="!showTable.length || showTable.indexOf('2')!== -1">
              <div class="title">{{$t('monitor.top5')}}</div>
              <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0">
                <thead>
                <tr>
                  <th><div class="cell" v-once>{{$t('monitor.top5Rank')}}</div></th>
                  <th><div class="cell" v-once>{{$t('public.agent')}}</div></th>
                  <th><div class="cell" v-once>{{$t('monitor.connectSessionNum')}}</div></th>
                  <th><div class="cell" v-once>{{$t('monitor.top5Complete')}}</div></th>
                </tr>
                </thead>
                <tbody class="el-table__body">
                <tr v-for="(item, index) in top5" >
                  <td><i class="iconfont top-red" :class="index ? ('icon-NO' + index):'icon-NO'"></i>&nbsp;{{index >2? (index+1) : ''}}</td>
                  <td>{{webchatPeers[item].agentNo}}</td>
                  <td>{{webchatPeers[item].sessionAccessCount}}</td>
                  <td>{{webchatPeers[item].sessionCompleteCount}}</td>
                </tr>
                </tbody>
              </table>
            </el-col>
          </el-row>
          <div class="block" v-if="!showTable.length || showTable.indexOf('3')!== -1">
            <div class="title">{{$t('monitor.webchat6Hour')}}<i class="iconfont icon-peizhi" @click="monitorWarn('service')"></i></div>
            <monitor-line ref="monitorLine1" :data="webchatInData"></monitor-line>
          </div>
          <div class="block" v-if="!showTable.length || showTable.indexOf('4')!== -1">
            <div class="title">{{$t('monitor.webchatChannel')}}<i class="iconfont icon-peizhi" @click="monitorWarn('channel')"></i></div>
            <monitor-column ref="column" :data="webchatChannelData"></monitor-column>
          </div>
        </el-main>
      </el-container>
      <warn-setting
        :type="dialogObj.type"
        :selectState="dialogObj.selectState"
        :data="dialogObj.data"
        :title="dialogObj.title"
        ref="warn"
        @save="save"
      ></warn-setting>
    </div>
  </div>
</template>
<script>
  import Affix from '../../ui-modules/affix/Affix'
  import monitorColumn from './base/monitorColumn'
  import monitorLine from './base/monitorLine'
  import warnSetting from './base/warnSetting'
  import monitorPie from './base/monitorPie'
  import {monitorWebchatConfig} from '@/utils/monitor'
  export default {
    name: 'callSummary',
    data () {
      return {
        showTable: [],
        showOptions: [
          {name: this.$t('monitor.webchatAgentMonitor'), value: '1'},
          {name: this.$t('monitor.top5'), value: '2'},
          {name: this.$t('monitor.webchat6Hour'), value: '3'},
          {name: this.$t('monitor.webchatChannel'), value: '4'}
        ],
        dialogObj: {
          type: '',
          selectState: [],
          data: [],
          title: ''
        },
        select: monitorWebchatConfig(),
        webchatInData: {
          xCategories: [],
          seriesArray: []
        },
        webchatChannelData: {
          xCategories: [],
          seriesArray: []
        },
        stamp: ''
      }
    },
    props: {
    },
    inject: ['commonData', 'init', 'webchatPeers', 'agentType'],
    components: {
      Affix,
      monitorColumn,
      warnSetting,
      monitorLine,
      monitorPie
    },
    filters: {
      rate (value, all) {
        if (all) {
          return Math.round(value * 100 / all) + '%'
        }
        return '0%'
      }
    },
    mounted () {
    },
    computed: {
      top5 () {
        let _array = Object.keys(this.webchatPeers)
        return _array.sort(this.sortArray).slice(0, 5)
      },
      pieData () {
        let state = this.$store.state.monitor.webchatAgentStatus
        let arr = []
        let on = 0
        let name = [
          {name: this.$t('monitor.claimOff'), value: 'close', color: '#5F89BB'},
          {name: this.$t('monitor.logout'), value: 'offline', color: '#9761ad'},
          {name: this.$t('monitor.sessionIdle'), value: 'free', color: '#79B05D'},
          {name: this.$t('monitor.sessionBusy'), value: 'busy', color: '#ED5870'}
        ]
        name.forEach((item) => {
          let data = {name: item.name, y: state[item.value], color: item.color}
          if (state[item.value]) {
            arr.push(data)
            if (item.value !== 'offline') {
              on += state[item.value]
            }
          }
        })
        return {pie: arr, on, out: state.offline}
      },
      summary () {
        return this.$store.state.monitor.webchatSummary
      }
    },
    methods: {
      sortArray (a, b) {
        let _sessionNumB = this.webchatPeers[b].sessionAccessCount
        let _sessionNumA = this.webchatPeers[a].sessionAccessCount
        return _sessionNumB - _sessionNumA
      },
      monitorWarn (type) {
        this.dialogObj.type = type
        this.dialogObj.title = this.select[type + 'Name']
        this.dialogObj.selectState = this.select[type]
        this.$store.dispatch('queryMonitorWarningCfg', {module: 'webchat'}).then((res) => {
          if (res.data && res.data.length) {
            this.dialogObj.data = res.data[0].config[type] || []
          }
          this.$refs.warn.open()
        })
      },
      save (data) {
        data.module = 'webchat'
        this.$store.dispatch('updateMonitorWarningCfg', data).then((res) => {
          this.$refs.warn.handleClose()
        })
      },
      initData (type) {
        // 只有在监控模块下才发请求
        if (this.$route.path.split('/')[2] === 'monitorNew') {
          this.getAdvisoryChannelCount(type)
        }
        this.getWebChatDataIn6Hours(type)
      },
      getWebChatDataIn6Hours (type) {
        if (type === 'init') {
          this.stamp = new Date().getTime()
        } else {
          this.stamp += 60000
        }
        this.$store.dispatch('getWebChatDataIn6Hours', {type: type, stamp: this.stamp}).then((res) => {
          if (type === 'init') {
            let datas = res.data || {}
            // let categoriesArray = []
            let seriesArray = []
            let headerConfig = {finish: this.$t('monitor.completeSessionNum'), invite: this.$t('monitor.activenvitation'), manual: this.$t('monitor.totalAccess'), queue: this.$t('monitor.waitingSessionNum')}
            let types = Object.keys(datas)
            // types.forEach(item => {
            //   let serie = { name: item.name, data: [], valueName: item.valueName }
            //   seriesArray.push(serie)
            // })
            for (let i = 0; i < types.length; i++) {
              let item = types[i]
              let currents = datas[item] || []
              let serie = { name: headerConfig[item], data: [], valueName: item }
              currents.forEach((one) => {
                let item = one.split(':')
                let time = parseInt(item[0])
                let num = parseInt(item[1])
                serie.data.push({x: time, y: num})
              })
              seriesArray.push(serie)
            }
            // this.webchatInData.xCategories = categoriesArray
            this.webchatInData.seriesArray = seriesArray
          } else {
            let datas = res.data || {}
            this.webchatInData.seriesArray.forEach((one) => {
              let item = datas[one.valueName][0].split(':')
              let time = parseInt(item[0])
              let num = parseInt(item[1])
              one.data.push({x: time, y: num})
            })
          }
        })
      },
      getAdvisoryChannelCount (type) {
        this.$store.dispatch('getAdvisoryChannelCount').then((res) => {
          let data = res.data || {}
          let seriesArray = []
          for (let i in data) {
            if (i !== '_id') {
              let name = this.select.channel.filter((item) => item.value === i)
              seriesArray.push({name: name[0].label, data: [data[i]], animation: false})
            }
          }
          this.webchatChannelData.xCategories = ['']
          this.webchatChannelData.seriesArray = seriesArray
          // if (this.$refs.column) {
          //   this.$refs.column.init({categoriesArray: [''], seriesArray: seriesArray})
          // }
        })
      }
    },
    activated () {
      if (this.$refs.monitorLine1) {
        this.$refs.monitorLine1.reflow()
      }
    },
    beforeMount () {
      this.init('webchatInit')
      this.initData('init')
      if (this.agentType === 'manager' || this.agentType === 'admin') {
        let self = this
        window.setInterval(() => {
          self.initData('update')
        }, 60000)
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl'
  .wrap
    padding 20px 10px 20px 10px
    box-sizing border-box
  .webchat-summary
    .main1
      margin-left: 175px
  .card
    width 150px
    margin-left: 3px
    padding 0 5px
    position absolute
    height: calc(100vh - 125px)
    .icon-peizhi
      position absolute
      right 10px
      font-size 16px
      top 10px
      color $c-main
      cursor pointer
    .card-item
      padding-bottom 8px
      border-bottom 1px dashed $c-border2
      text-align center
      &:last-child
        border 1px dashed #fff
      .num
        font-size 18px
        color $cf-gray1
        font-weight bold
        padding 5px 0 2px
      .num-word
        font-size 14px
        color $cf-gray4
  .main
    padding-top 0px
    padding-left 30px
    overflow-x hidden
    .border-line
      border-right 1px dashed $c-border1
      padding-right 30px
    .header
      padding-bottom 15px
    .title
      padding-bottom 16px
      font-size 14px
      color $cf-gray1
      .icon-peizhi
        padding-left 4px
        font-size 16px
        color $c-main
        cursor pointer
    .agent
      padding-bottom 16px
    .block
      padding-top 35px
  .square-wrap
    padding-top 10px
  .top-red
    color $c-pink
  .agent-cont
    border: 1px solid #e6e6e6;
    margin-right: 20px;
    margin-top: 10px;
    padding: 5px 15px;
    float: left;
    font-size 14px
    border-radius: 4px;
  .agent-title
    padding-right 10px
    color $c-main
  .padding-r
    padding-right 10px
    padding-top 20px
  .pie
    text-align center
    .pie-out
      display inline-block
      padding-right:10px
      margin-right: 10px
      border-right 1px solid $cf-gray4
  .icon-wenzishuoming
    color $c-main
    margin 0 5px
  .tips
    padding 20px 0 10px
    color $c-prompt
  .header-time
    font-size 13px
  .mulit-select
    width 200px
</style>
